package com.hopu.v1.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hopu.v1.pojo.common.R;
import com.hopu.v1.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * jgb
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }
        System.out.println("interceptor");
        String token = request.getHeader("token");
        System.out.println("front interceptor");
        String frontToken = request.getHeader("frontToken");
        if(token==null && frontToken==null){
            response.setStatus(400);
            R r = R.err("请先登录");
            String json = new ObjectMapper().writeValueAsString(r);
            response.getWriter().write(json);
            return false;
        }
        if (token!=null)
            JwtUtils.getUserId(token);
        else
            JwtUtils.getUserId(frontToken);
        return true;
    }
}
